package ch.il07.converter.persistance.tests;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

import org.junit.Before;
import org.junit.Test;

import ch.il07.converter.persistence.Persistence;
import ch.il07.converter.persistence.PersistenceHelper;
import ch.il07.converter.persistence.entities.AccessLevel;
import ch.il07.converter.persistence.entities.Measurand;
import ch.il07.converter.persistence.entities.Unit;
import ch.il07.converter.persistence.exceptions.PersistenceException;
import ch.il07.utils.RandomHelper;

public class PublishMeasurandAndUnit {
	
	private Persistence persistence;
	
	@Before
	public void init() throws PersistenceException {
		persistence = PersistenceHelper.getPersistence();
	}
	
	@Test
	public void publishMeasurand() throws PersistenceException {
		String username = RandomHelper.randString();
		String measurandName = RandomHelper.randString();
		
		persistence.addUser(username, RandomHelper.getEmail(username), username, AccessLevel.USER);
		persistence.addMeasurand(new Measurand(measurandName, new Unit(RandomHelper.randString(), 1.0)), username);
		Measurand m = persistence.getMeasurand(measurandName, username);
		Unit oldDefaultUnit = m.getDefaultUnit();
		assertNotNull("default unit should be private, since measurand is so", oldDefaultUnit.getOwner());
		
		// should publish the measurand
		m.setOwner(null);
		persistence.updateMeasurand(m);
		
		Measurand updatedMeasurand = persistence.getMeasurand(measurandName, null);
		assertNotNull("should be able to get it without username since it's been published", updatedMeasurand);
		Unit defaultUnit = updatedMeasurand.getDefaultUnit();
		assertNotNull("default unit should not have been made public", defaultUnit.getOwner());
	}
	
	@Test
	public void publishUnit() throws PersistenceException {
		String username = RandomHelper.randString();
		String measurandName = RandomHelper.randString();
		
		persistence.addUser(username, RandomHelper.getEmail(username), username, AccessLevel.USER);
		persistence.addMeasurand(new Measurand(measurandName, new Unit(RandomHelper.randString(), 1.0)), username);
		Measurand m = persistence.getMeasurand(measurandName, username);
		
		Unit defaultUnit = m.getDefaultUnit();
		assertNotNull("default unit should have set it's username", defaultUnit.getOwner());
		defaultUnit.setOwner(null);
		
		persistence.updateUnit(m, defaultUnit);
		
		// now try to get the measurand with unit again, and check whether it's all updated correctly
		Measurand updatedOne = persistence.getMeasurand(measurandName, username);
		Unit updatedDefaultUnit = updatedOne.getDefaultUnit();
		assertNull("default unit should have been published", updatedDefaultUnit.getOwner());
	}
}
